<template>
  <view>
    <view calss="Chatsettings" style="width: 100vw;height:100vh;background-color: #f3f3f3;overflow-y: auto;">
      <up-navbar title="群聊设置" @leftClick="close" placeholder></up-navbar>
      <view style="padding-right: 20rpx;padding-left: 20rpx;padding-top: 20rpx;">
        <scroll-view class="Chatsettings-info">
          <!-- 用户头像和信息 -->
          <view class="user-info" v-if="displayedMembers.length !== 0">
            <view class="user-details">
              <!-- 群成员头像展示 (最多两行，每行5个) -->
              <view class="member-grid">
                <view v-for="(member, index) in displayedMembers" :key="index" class="member-item">
                  <view class="member-avatar" @click="jumpPerson(member)">
                    <up-image v-if="member.avatar" :src="member.avatar" width="80rpx" height="80rpx" radius="10rpx">
                      <template #error>
                        <view style="width: 100%; height: 100%;">
                          <text class="pic-text">{{ showUserName(member.username) }}</text>
                        </view>
                      </template>
                    </up-image>
                    <view v-else class="avatar-text">{{ showUserName(member.username) }}</view>
                  </view>
                  <text class="member-name">{{ member.username }}</text>
                  <text class="member-name" style="background: #eeeff1;border-radius: 12%;width: 57%;color: #88929b;position: relative;
                    font-size: 10px;" v-if="member.group_role">
                    {{ getRoleText(member.group_role) }}
                  </text>
                </view>

                <view class="member-item" v-if="judgeInfo" @click="Initiateanevent">
                  <view class="user-avatar">
                    <up-icon name="plus"></up-icon>
                  </view>
                  <view class="user-text">
                    <view class="member-name">添加</view>
                  </view>
                </view>
                <view class="member-item" v-if="judgeInfo" @click="removeMember">
                  <view class="user-avatar">
                    <up-icon name="minus"></up-icon>
                  </view>
                  <view class="user-text">
                    <view class="member-name">移除</view>
                  </view>
                </view>
              </view>

              <!-- 查看全部群成员 -->
              <view class="view-all-members" @click="openMemberList">
                <text>查看全部群成员({{ imgheadList.length }})</text>
                <up-icon name="arrow-right" size="14"></up-icon>
              </view>
            </view>
          </view>

          <!-- 搜索 + 功能 -->
          <view class="Chatsettings-find">

            <view class="find-input" @click="searchforClick">
              <up-icon name="search" class="find-icon"></up-icon>
              <view calss="find-name">搜索聊天记录</view>
            </view>

            <view class="find-results">
              <view class="find-item" @click="searchforClick">
                <image src="@/static/chat/ltjl.png" mode="aspectFill" class="find-item-image" />
                <text class="find-item-text">聊天记录</text>
              </view>

              <view class="find-item" @click="viewImgClick">
                <image src="@/static/chat/tupian.png" mode="aspectFill" class="find-item-image" />
                <text class="find-item-text">图片和视频</text>
              </view>

              <view class="find-item" @click="viewFileDirClick">
                <image src="@/static/chat/wenjian.png" mode="aspectFill" class="find-item-image" />
                <text class="find-item-text">文件</text>
              </view>
            </view>
          </view>

          <view class="Chatsettings-function">
            <view class="function-item">
              <view class="function-left">
                <text>置顶会话</text>
              </view>
              <view class="function-right">
                <up-switch v-model="Topupconversation" @change="TopupconversationChange" />
              </view>
            </view>

            <view class="function-item">
              <view class="function-left">
                <text>消息免打扰</text>
              </view>
              <view class="function-right">
                <up-switch v-model="Messagefree" @change="MessagefreeChange" />
              </view>
            </view>
          </view>

          <view class="Chatsettings-dangerzone">
            <view class="danger-item" @click="leaveGroupChat" v-if="isGroupLeader != 99">
              退出群聊
            </view>
            <view class="danger-item" @click="disbandGroup" v-if="isGroupLeader == 99">
              解散该群
            </view>
          </view>

        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { chatApi } from '@/apis/cloud/chat';
import OrgPicker from "@/components/OrgPicker/index.vue";
import { useChatsettings, useChatStore, useGroupStore, useUserStore } from '@/pinia-store/user';
import { objectToFormData } from "@/utils/chat";
import { mapStores } from 'pinia';
export default {
  name: "Chatsettings",
  props: {},
  components: {
    OrgPicker,
  },
  data () {
    return {
      Topupconversation: false, // 置顶会话
      Messagefree: false, // 消息免打扰
      groupOptions: [
        { label: '置顶', value: 'top', disabled: true },
        { label: '单聊', value: 'single', disabled: true },
        { label: '群聊', value: 'group', disabled: false },
        { label: '消息免打扰', value: 'no-disturb', disabled: true },
        { label: '工作', value: 'work', disabled: true },
        { label: '功能', value: 'feature', disabled: true }
      ],
      selectedGroup: 'group', // 当前选中的分组
      friend: null,
      imInfo: null,
      userInfo: null,
      dialogId: null,
      dialogid: null, // 对话ID
      maxDisplayMembers: 9,
      memberListShow: false, // 群成员弹窗显示状态
      navbarHeight: 44, // 导航栏高度
      searchBarHeight: 50, // 搜索栏高度
      imgheadList: [],
      infoId: null, // 登录人ID
      isGroupLeader: '',
      andaddpersonnel: null,
      Chatsettings: null,
      group: null,
    }
  },
  computed: {
    ...mapStores(useChatStore, useUserStore, useGroupStore, useChatsettings),
    // 显示群成员 最多显示9个
    displayedMembers () {
      return this.imgheadList.slice(0, this.maxDisplayMembers);
    },
    // 筛选群人员
    filteredMembers () {
      if (!this.memberSearchKeyword) {
        return this.imgheadList;
      }
      // 过滤筛选
      return this.imgheadList.filter(member => {
        return member.username.includes(this.memberSearchKeyword)
      });
    },
    judgeInfo () {
      // 判断是否是群主
      return this.imgheadList.some(member => {
        return (member.group_role == 99 || member.group_role == 98) && member.id === this.infoId;
      });
    },
  },
  onLoad () {
    this.imInfo = this.chatStore.imInfo;// 当前登录用户
    this.userInfo = this.userStore.user;
    this.infoId = this.chatStore.imInfo.id
    this.group = this.groupStore.group;
    this.getGroupMember()
    this.getGroupRole()
  },
  onShow () {
    const updated = uni.getStorageSync('groupMemberUpdated')
    if (updated) {
      // 刷新群成员数据
      this.getGroupMember()

      // 清除标记，避免下次重复刷新
      uni.removeStorageSync('groupMemberUpdated')
    }
  },
  created () {
    if (!this.Chatsettings) {
      this.Chatsettings = useChatsettings()
    }
    uni.$off('groupchatMemberPicker');
    uni.$on('groupchatMemberPicker', (data) => {
      this.addMember(data)
    })
    uni.$off('groupchatRemoveMemberPicker');
    uni.$on('groupchatRemoveMemberPicker', (data) => {
      this.handleRemoveMember(data)
    })

    uni.$off('CreateGroupMemberPicker');
    uni.$on('CreateGroupMemberPicker', (data) => {
      this.addMember(data)
    })
  },
  methods: {
    // 获取角色文本
    getRoleText (role) {
      return role == 99 ? '群主' : role == 98 ? '管理员' : ''
    },
    // 查看群成员
    openMemberList () {
      uni.navigateTo({
        url: '/pages/chat/message/group/Groupchatmembers'
      })
    },
    // 添加成员
    Initiateanevent () {
      let that = this
      uni.navigateTo({
        url: `/pages/chat/list/MemberPicker?ShowHide=true`,
        success: function (res) {
          res.eventChannel.emit('groupchat', {
            imgheadList: JSON.stringify(that.imgheadList),
            userInfo: JSON.stringify(that.userInfo),
            source: 'groupchat',
          })
        }
      })
    },
    // 移除成员
    removeMember () {
      let that = this
      uni.navigateTo({
        url: `/pages/chat/message/group/groupMemberPicker`,
        success: function (res) {
          res.eventChannel.emit('groupchatremove', {
            imgheadList: JSON.stringify(that.imgheadList),
            userInfo: JSON.stringify(that.userInfo),
            source: 'groupchatremove'
          })
        }
      })
    },
    async addMember (data) {
      uni.showLoading({
        title: '添加成员中...',
        mask: true // 防止触摸穿透
      });
      setTimeout(async () => {
        const selectedMembers = JSON.parse(data);

        // 筛选出选中的成员
        const newMembers = selectedMembers.filter(selected => {
          return !this.imgheadList.some(existing =>
            this.getUserKey(existing) === this.getUserKey(selected)
          );
        });

        if (newMembers.length == 0) {
          // 判断是否是因为未选择成员还是因为重复
          const hasSelectedMembers = selectedMembers.length > 0;
          const toastMessage = hasSelectedMembers
            ? "所选成员已存在，请勿重复添加"
            : "请添加成员后再提交";

          uni.$u.toast(toastMessage);
          uni.hideLoading(); // 关闭加载提示
          return
        }
        const memberArr = newMembers.map(item => {
          return `${item.username || item.name}|${item.account || ''}|${item.id}`
        })

        let params = {
          data: {
            groupId: this.group.group_id,
            account: this.imInfo.account,
            token: this.userInfo.token,
            memberArr: memberArr,

          },
          url: 'index.php/users/Group/joinGroup'
        }
        const msg = await chatApi(this.userInfo.token, objectToFormData(params));
        if (msg.code == 200) {
          uni.hideLoading(); // 先关闭加载
          this.getGroupMember()
          uni.$u.toast('添加成员成功')
        } else {
          uni.hideLoading();
          uni.$u.toast(msg.msg || '添加失败'); // 显示错误信息
        }
      }, 500);
    },
    getUserKey (item) {
      return item.cloud_worker_id || item.uid || item.id;
    },
    async handleRemoveMember (data) {
      uni.showLoading({
        title: '移除成员中...',
        mask: true // 防止触摸穿透
      });

      const selectedMembers = JSON.parse(data);

      if (selectedMembers.length == 0) {
        uni.$u.toast('请选择成员移除')
        return
      }
      const memberArr = selectedMembers.map(item => {
        return `${item.id}`
      })

      let params = {
        data: {
          groupId: this.group.group_id,
          account: this.imInfo.account,
          token: this.userInfo.token,
          uidArr: memberArr,
        },
        url: 'index.php/users/Group/removeMembers'
      }
      const msg = await chatApi(this.userInfo.token, objectToFormData(params));
      if (msg.code == 200) {
        uni.hideLoading(); // 先关闭加载
        this.getGroupMember()
        uni.$u.toast('移除成员成功')
      } else {
        uni.hideLoading();
        uni.$u.toast(msg.msg || '移除失败'); // 显示错误信息
      }

    },
    // 搜索聊天记录
    searchforClick () {
      uni.navigateTo({
        url: '/pages/chat/message/group/Groupchathistory'
      })
    },
    // 置顶会话
    TopupconversationChange (e) {
      this.Topupconversation = e
    },
    // 消息免打扰
    MessagefreeChange (e) {
      this.Messagefree = e
    },
    // 退出群聊
    async leaveGroupChat () {
      let that = this
      uni.showModal({
        title: '提示',
        content: '确认退出群聊吗？',
        showCancel: true,
        cancelColor: "#555",
        confirmColor: "#eb0909",
        confirmText: "确定",
        async success (res) {
          if (res.confirm) {
            uni.showLoading({
              title: '请稍等...'
            });
            let params = {
              data: {
                groupId: that.group.group_id,
                uid: that.chatStore.imInfo.id,
              },
              url: 'index.php/users/Group/leaveGroup'
            }
            const msg = await chatApi(that.userInfo.token, objectToFormData(params))
            if (msg.code == 200) {
              uni.hideLoading();
              uni.$u.toast('退出群聊成功')
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/chat/list/index'
                })
              })
            } else {
              uni.hideLoading();
              uni.$u.toast(msg.msg || '退出群聊失败')
            }
          }
        }
      })
    },
    // 解散群聊
    async disbandGroup () {
      let that = this
      uni.showModal({
        title: '提示',
        content: '确认解散群聊吗？',
        showCancel: true,
        cancelColor: "#555",
        confirmColor: "#eb0909",
        confirmText: "确定",
        async success (res) {
          if (res.confirm) {
            uni.showLoading({
              title: '请稍等...'
            });
            let params = {
              data: {
                groupId: that.group.group_id,
                uid: that.chatStore.imInfo.id,
              },
              url: 'index.php/users/Group/disbandGroup'
            }
            const msg = await chatApi(that.userInfo.token, objectToFormData(params))
            if (msg.code == 200) {
              uni.hideLoading();
              uni.$u.toast('解散成功')
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/chat/list/index'
                })
              })
            } else {
              uni.hideLoading();
              uni.$u.toast(msg.msg || '解散失败')
            }
          }
        }
      })
    },
    // 打开文件和链接弹窗
    viewFileDirClick () {
      uni.navigateTo({
        // url: '/pages/chat/message/group/Groupchatfiles'
        url: `/pages/chat/message/common/chatGroupFolder?groupId=${this.group.group_id}&groupName=${this.group.group_name}`
      })
    },
    // 关闭聊天设置弹窗
    close () {
      uni.navigateBack();
    },
    viewImgClick () {
      uni.navigateTo({
        // url: '/pages/chat/message/group/Groupchatpictures',
				url: '/pages/chat/message/common/chatImgHistory?groupId='+this.group.group_id
      })
    },
    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
    // 获取头像
    async getGroupMember () {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        const params = {
          'data[groupId]': this.group.group_id,
          'data[account]': this.imInfo.account,
          'data[token]': this.userInfo.token,
          'data[myAccount]': this.imInfo.account,
          'data[page]': 1,
          'data[pageSize]': 1000,
          'data[friendAccount]': this.friend?.friend_account,
          url: 'index.php/users/Group/getGroupMember.html'
        }

        const msg = await chatApi(this.userInfo.token, params);
        if (msg.code == 200) {
          this.imgheadList = msg.data;
          this.Chatsettings.setselection(msg.data)
          uni.setStorageSync('Groupchatmembers', JSON.stringify(this.imgheadList));
        }
        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
      }
    },
    // 获取权限
    async getGroupRole () {
      const params = {
        'data[groupId]': this.group.group_id,
        'data[uid]': this.chatStore.imInfo.id,
        url: 'index.php/users/group/getUserGroupRole.html'
      }

      const msg = await chatApi(this.userInfo.token, params);

      if (msg.code == 200) {
        this.isGroupLeader = msg.data.group_role
      }
    },
    jumpPerson (e) {
      let params = {
        id: e.wid,
        name: e.username,
        type: 'user',
        avatar: e.avatar
      }
      uni.navigateTo({
        url: '/pages/addressBook/details/grdetails',
        animationType: 'none',
        success: function (res) {
          res.eventChannel.emit('details', { item: params })
        }
      });
    },
  }
}
</script>

<style scoped lang="scss">
// 聊天设置
.Chatsettings-info {
  //margin: 20rpx;
  overflow-y: auto;

  .user-info {
    padding: 15rpx;
    display: flex;
    border-radius: 20rpx;
    background-color: #ffffff;
    margin-bottom: 30rpx;

    .user-details {
      width: 100%;

      .user-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 15%;
        overflow: hidden;
        background: #f3f3f3;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 4rpx 10rpx 10rpx 10rpx;

        img {
          width: 100%;
          /* 图片宽度占满容器 */
          height: 100%;
          /* 图片高度占满容器 */
          border: none;
          /* 去除边框 */
          object-fit: cover;
          /* 图片适配容器，保持比例 */
        }
      }

      .member-grid {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        margin-bottom: 20rpx;

        .member-item {
          width: 20%; // 每行5个
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-bottom: 20rpx;

          .member-avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 10rpx;
            background-color: #3d85fc;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            margin-bottom: 8rpx;

            .avatar-image {
              width: 100%;
              height: 100%;
            }

            .avatar-text {
              color: #ffffff;
              font-size: 28rpx;
            }
          }

          .member-name {
            font-size: 24rpx;
            color: #333;
            text-align: center;
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }

      .view-all-members {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #0189FF;
        font-size: 26rpx;
        padding: 10rpx 0;
        border-top: 1rpx solid #f5f5f5;
      }
    }
  }


  .Chatsettings-find {
    padding: 10rpx;
    display: flex;
    flex-direction: column;
    height: 18vh;
    border-radius: 20rpx;
    background-color: #ffffff;
    margin-bottom: 30rpx;

    .find-input {
      display: flex;
      align-items: center;
      margin: 10rpx;
      padding: 5rpx;
      background: #f3f3f3;
      height: 4vh;
      border-radius: 10rpx;

      .find-icon {
        padding-left: 10rpx;
        padding-right: 10rpx;

        :deep(.u-icon__icon) {
          font-size: 50rpx !important;
        }
      }

      .find-name {
        color: #9b9c9d;
      }
    }

    .find-results {
      display: flex;
      padding: 0 20rpx;
    }

    .find-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20rpx 20rpx;

      &:active {
        background-color: #f5f5f5;
        border-radius: 10%;
      }

      .find-item-image {
        width: 60rpx;
        height: 60rpx;
        margin-bottom: 10rpx;
      }

      .find-item-text {
        font-size: 24rpx;
        color: #333;
        text-align: center;
      }
    }
  }


  .Chatsettings-function {
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 0 20rpx;
    margin-bottom: 30rpx;

    .function-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 25rpx 0;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .function-left {
        font-size: 28rpx;
        color: #333;
      }

      .function-right {
        display: flex;
        align-items: center;
        font-size: 26rpx;
        color: #666;

        .arrow-icon {
          margin-left: 10rpx;

          :deep(.u-icon__icon) {
            font-size: 24rpx;
          }
        }
      }
    }
  }


  .Chatsettings-quickbar {
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 0 20rpx;
    margin-bottom: 30rpx;

    .function-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx 0;

      .function-left {
        display: flex;
        flex-direction: column;
        justify-content: center;

        .title {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
        }

        .desc {
          font-size: 24rpx;
          color: #999;
        }
      }

      .function-right {
        display: flex;
        align-items: center;
      }
    }
  }


  .Chatsettings-dangerzone {
    background-color: #ffffff;
    border-radius: 20rpx;

    .danger-item {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28rpx;
      color: #e60000; // 钉钉风格红色
      padding: 30rpx 0;
      border-bottom: 2rpx solid #f5f5f5;

      &:active {
        background-color: #f5f5f5;
        border-radius: 16rpx;
      }
    }
  }
}
</style>
